<script setup>
import { onLoad, onShow } from "@dcloudio/uni-app";
import { onMounted, ref, watch } from "vue";
import { clothesListApi, clothesDelApi,clothesRecommendedApi } from "@/apis/clothes.js"
import { useUserStore } from "@/stores/userStore.js"
import { getPredictApi } from "@/apis/weather.js"
import { getCityList } from '@/apis/city.js'

const userStore = useUserStore();
const list = ref();
const forecasts = ref();
const cList = ref();
// 默认41-->广州
const selectVal = ref(40);

const recommend = ref();
onMounted(async () => {
  // 默认广州
  const predictRes = await getPredictApi('CT20241029105032075')
  forecasts.value = predictRes.data
  const cityRes = await getCityList()
  cList.value = cityRes.data
  const recommendRes = await clothesRecommendedApi()
  console.log("推荐的",recommendRes.data);
  recommend.value = recommendRes.data
})

onShow(async() => {
  const res = await clothesListApi()
  list.value = res.data;
})

const show = ref(false)
// 上传图片
const uploadImg = (listIndex,clothesType) => {
    uni.chooseImage({
        count: 9, // 默认9，设置图片选择的最大数量
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'], // 从相册选择
        success: async(res) => {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          // 将当前图片直接上传到后台
          const user = userStore.getUserInfo()
          for (let i = 0; i < res.tempFilePaths.length; i++) {
            const clothId = generateClothId()
            const imgRes = await uni.uploadFile({
              url: `http://localhost:6999/change/upload/${clothesType}/${clothId}/${user.userId}`,
              filePath: res.tempFilePaths[i],
                name: 'file',
                header: {
                    'token': `${uni.getStorageSync('token')}`
                }
            });
            // 这是临时动态
            if (imgRes.statusCode === 200) {
              list.value[listIndex].chooseImags = [...list.value[listIndex].chooseImags,{'imageUrl':JSON.parse(imgRes.data).imgUrl,'imageId':JSON.parse(imgRes.data).imageId}];
            }
          }     
        },
        fail: (err) => {
          // 用户取消选择或发生错误时执行的回调函数
          console.error(err);
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      });
}

const camera = () => {
  uni.navigateTo({
    url:'/pages/takePhotos/takePhotos?type=photo'
  })
}

//反馈,图片放大预览
const handlePrevewImage = (url,listIndex) => {
    //先构造要预览的图标数组
    const urls = list.value[listIndex].chooseImags
    //接收传递过来的图片url
    const current = url;
    wx.previewImage({
        current, // 当前显示图片的http链接
        urls // 需要预览的图片http链接数组列表
    })
}

//删除data里面图片的方法
const bandleRemoveImg = async(listIndex,index,imageId) => {
    const res  = await clothesDelApi({'imageId':imageId})
    //2.获取data中的图片数组
    const chooseImagsData = list.value[listIndex].chooseImags
    //3.根据索引删除元素
    chooseImagsData.splice(index, 1);
    //4.重新填充会chooseImags中
    list.value[listIndex].chooseImags = chooseImagsData;
}
const scan = ()=>{
  uni.navigateTo({
    url:'/pages/takePhotos/takePhotos?type=scan'
  })
}

const generateClothId = () =>{
  const now = new Date();
  const y = now.getFullYear();
  const m = (now.getMonth() + 1).toString().padStart(2, '0');
  const d = now.getDate().toString().padStart(2, '0');
  const h = now.getHours().toString().padStart(2, '0');
  const i = now.getMinutes().toString().padStart(2, '0');
  const s = now.getSeconds().toString().padStart(2, '0');
  const ms = now.getMilliseconds().toString().padStart(3, '0');
  return `CL${y}${m}${d}${h}${i}${s}${ms}`;
}

const selectCity = async(e) => {
  const fore = await getPredictApi(cList.value[e].text)
  forecasts.value = fore.data
}

</script>

<template>
  <div class="header">
    <uni-icons type="scan" size="30" @click="scan"></uni-icons>
    <!-- <uni-tag :text="forecasts.city" type="primary" style="transform: translate(0,+10%);"/> -->
      <uni-data-select style="width: 25%;"
        v-model="selectVal"
        :localdata="cList"
        :clear="false"
        @change="selectCity"
      ></uni-data-select>
    
    <swiper class="weather-swiper" circular=true autoplay=true vertical=true disable-touch=true>
				<swiper-item v-for="item in forecasts" :key="item.date">
          {{ item.predictDate }} {{ item.dayTemp }}°C {{ item.dayWeather }} 
          <!-- 风向 {{ item.dayWind }} 风速 {{ item.dayPower }} -->
        </swiper-item>
		</swiper>
    <uni-icons type="camera" size="30" @click="camera"></uni-icons>
  </div>
  <!-- 全部 -->
  <div class="container">
    <!-- 大选项们 -->
    <uni-collapse accordion v-model="accordionVal">
      <!-- 大选项 -->
      <uni-collapse-item
        v-for="(item,listIndex) in list"
        :title="item.clothesType"
        :key="0"
      >
        <view class="Upload_module">
                <view class="layout">
                    <view class="picture_list">
                        <!-- 图片 -->
                        <view v-for="(c,index) in item.chooseImags" :key="index">
                            <view @tap="handlePrevewImage(c.imageUrl,listIndex)" class="cu-avatar view"
                                :style="{ 'backgroundImage': 'url(' + c.imageUrl + ')' }"/>
                            <image class="delete" @tap="bandleRemoveImg(listIndex,index,c.imageId)" mode="widthFix"
                                src="@/static/images/delete.png"></image>
                        </view> 

                        <!-- 上传按钮 -->
                        <view class="uploadImg" @click="uploadImg(listIndex,item.clothesType)">
                            <view class="image">
                                <image src="@/static/images/upload.png" mode="widthFix">
                                </image>
                            </view>
                        </view>
                    </view>
                </view>
            </view>

      </uni-collapse-item>
    </uni-collapse>
  </div>
  <!-- 悬浮按钮 -->
  <uni-fab :content="recommend" horizontal="right" vertical="bottom"
  direction="horizontal"/>
</template>

<style scoped  lang="scss">

.header {
    margin: 2rpx 10rpx 2rpx 10rpx;
    height: 7%;
    position: sticky;
    z-index: 100;
    top: 0;
    display: flex;
    border-radius: 10rpx;
    border-bottom: 2rpx solid #f1f3f4;
    background: #fff;
    justify-content: space-between;
}

.container {
  margin: 10rpx;
  border: 1rpx solid white;
  border-radius: 10px;
  overflow: hidden;
}

.uni-flex {
  background-color: #f5f5f5;
  display: flex;
  flex-direction: row;
  justify-content: space-between; /* 项目之间均匀分布 */
  flex-wrap: wrap; /* 允许子项换行 */
}
.grid-image{
  width: 150rpx;
  height: 150rpx;
  margin: 10rpx; /* 设置图片之间的间隔 */
}

.cu-avatar {
    font-variant: small-caps;
    margin: 0;
    padding: 0;
    display: inline-flex;
    text-align: center;
    justify-content: center;
    align-items: center;
    background-color: #ccc;
    color: #ffffff;
    white-space: nowrap;
    position: relative;
    width: 64upx;
    height: 64upx;
    background-size: cover;
    background-position: center;
    vertical-align: middle;
    font-size: 1.5em;
}

.picture_list {
        display: flex;
        flex-wrap: wrap;

        .delete {
            position: absolute;
            right: 5px;
            z-index: 10;
            top: 5px;
            width: 16px;
            height: 16px;
            border-radius: 2px;
        }

        view {
            width: 154rpx;
            margin-right: 20rpx;
            margin-bottom: 20rpx;
            height: 154rpx;
            position: relative;

            .cover {
                position: absolute;
                height: 44rpx;
                line-height: 44rpx;
                background: rgba(0, 0, 0, 0.4);
                bottom: 0;
                left: 0;
                font-size: 24rpx;
                margin: 0 !important;
                border-bottom-left-radius: 12rpx;
                border-bottom-right-radius: 12rpx;
            }

            image,
            .view {
                width: 154rpx;
                height: 154rpx;
                border-radius: 12rpx;
            }
        }
    }

    .delete_img {
        position: absolute;
        right: 10rpx;
        z-index: 10;
        top: 10rpx;
        width: 32rpx;
        height: 32rpx;
        border-radius: 4rpx;
    }

    .Upload_module {

        .uploadImg {
            width: 150rpx;
            height: 150rpx;
            border: 2rpx solid #dfdfdf;
            border-radius: 12rpx;
            background: #fff;
            display: flex;
            align-items: center;
            justify-content: center;

            .image {
                display: flex;
                justify-content: center;
                align-items: center;

                image {
                    margin-left: 16rpx;
                    margin-top: 20rpx;
                    width: 60rpx;
                    height: 60rpx;
                }
            }
        }

        .layout {
            display: flex;
            align-items: center;
        }
    }
.weather-swiper {
  transform: translate(0,+15%);
  width: 50%;
  height: 30px;
}
</style>
